import csv
from datetime import datetime, time

# 定义交易时间窗口
trade_window_1_start = time(9, 30)
trade_window_1_end = time(11, 30)
trade_window_2_start = time(13, 0)
trade_window_2_end = time(15, 0)

# 用于存储每分钟的数据
minute_data = []

# 打开并读取CSV文件
with open('f.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file)

    # 初始化变量用于聚合数据
    current_minute = None
    open_px = None
    high_px = None
    low_px = None
    close_px = None
    business_count = 0
    business_amount = 0.0
    business_balance = 0.0

    for row in csv_reader:
        timestamp = datetime.strptime(row['data_timestamp'], '%H:%M:%S').time()
        last_px = float(row['last_px'])
        business_count += int(row['business_count'])
        business_amount += float(row['business_amount'])
        business_balance += float(row['business_balance'])

        if (trade_window_1_start <= timestamp <= trade_window_1_end) or (trade_window_2_start <= timestamp <= trade_window_2_end):
            # 如果时间在指定的交易时间窗口内
            if current_minute is None:
                # 初始化新的分钟
                current_minute = timestamp
                open_px = last_px
                high_px = last_px
                low_px = last_px

            high_px = max(high_px, last_px)
            low_px = min(low_px, last_px)
            close_px = last_px

            if timestamp > current_minute:
                # 当分钟变化时，保存数据并初始化新分钟
                minute_data.append({
                    'Minute': current_minute.strftime('%H:%M'),
                    'Open_px': open_px,
                    'High_px': high_px,
                    'Low_px': low_px,
                    'Close_px': close_px,
                    'Business_Count': business_count,
                    'Business_Amount': business_amount,
                    'Business_Balance': business_balance
                })

                # 重置变量
                current_minute = timestamp
                open_px = last_px
                high_px = last_px
                low_px = last_px
                business_count = int(row['business_count'])
                business_amount = float(row['business_amount'])
                business_balance = float(row['business_balance'])

# 打印每分钟的数据
for data in minute_data:
    print(f"Minute: {data['Minute']}, Open_px: {data['Open_px']:.2f}, High_px: {data['High_px']:.2f}, Low_px: {data['Low_px']:.2f}, Close_px: {data['Close_px']:.2f}, Business_Count: {data['Business_Count']}, Business_Amount: {data['Business_Amount']:.2f}, Business_Balance: {data['Business_Balance']:.2f}")
